package com.cmes.core.context.security;

import com.cmes.core.utils.StringPool;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上下文
 *
 * @author Bruce.Gong
 */
public class SecurityContextHolder {

    private static final String LOGIN_TYPE_KEY = "__login_type__";
    private static final String USER_ID_KEY = "__user_id__";
    private static final String USER_NAME_KEY = "__user_name__";
    private static final String REAL_NAME_KEY = "__real_name__";
    private static final String USER_KEY = "__user__";
    private static final String TOKEN_KEY = "__token__";
    private static final String TRACE_ID_KEY = "__trace_id__";

    private static final ThreadLocal<Map<String, Object>> LOCAL = new InheritableThreadLocal<Map<String, Object>>() {
        @Override
        protected Map<String, Object> initialValue() {
            return new ConcurrentHashMap<>(4);
        }
    };

    /**
     * 设置当前登录用户
     *
     * @param userId 用户ID
     * @param userName 用户名
     */
    public static void setCurrentUser(String loginType, Long userId, String userName, String realName) {
        LOCAL.get().put(LOGIN_TYPE_KEY, loginType);
        LOCAL.get().put(USER_ID_KEY, userId);
        LOCAL.get().put(USER_NAME_KEY, userName);
        LOCAL.get().put(REAL_NAME_KEY, realName);
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 登录用户ID
     */
    public static Long getCurrentUserId() {
        return Optional.ofNullable((Long) LOCAL.get().get(USER_ID_KEY)).orElse(-1L);
    }

    /**
     * 获取当前登录用户名
     *
     * @return 登录用户名
     */
    public static String getCurrentUserName() {
        return Optional.ofNullable((String) LOCAL.get().get(USER_NAME_KEY)).orElse(StringPool.EMPTY);
    }

    /**
     * 获取当前登录用户名
     *
     * @return 登录用户名
     */
    public static String getCurrentRealName() {
        return Optional.ofNullable((String) LOCAL.get().get(REAL_NAME_KEY)).orElse(StringPool.EMPTY);
    }

    /**
     * 设置Token
     *
     * @param token token
     */
    public static void setToken(String token) {
        LOCAL.get().put(TOKEN_KEY, token);
    }

    /**
     * 获取当前Token
     *
     * @return token
     */
    public static String getToken() {
        return (String) LOCAL.get().get(USER_KEY);
    }

    /**
     * 设置TraceId
     *
     * @param traceId traceId
     */
    public static void setTraceId(String traceId) {
        LOCAL.get().put(TRACE_ID_KEY, traceId);
    }

    /**
     * 获取当前TraceId
     *
     * @return TraceId
     */
    public static String getTraceId() {
        return Optional.ofNullable((String) LOCAL.get().get(TRACE_ID_KEY)).orElse(StringPool.EMPTY);
    }

}
